"""
面试管理序列化器
"""
from rest_framework import serializers
from django.utils import timezone
from .models import (
    InterviewCategory, InterviewQuestion, InterviewApplication,
    Interview, InterviewResult, InterviewEvaluation, InterviewTask,
    PracticeSession, PracticeMessage, PracticeRecord
)
from students.models import Student
from accounts.models import User


class InterviewCategorySerializer(serializers.ModelSerializer):
    """面试分类序列化器"""
    
    class Meta:
        model = InterviewCategory
        fields = '__all__'


class InterviewQuestionSerializer(serializers.ModelSerializer):
    """面试题目序列化器"""
    
    category_name = serializers.CharField(source='category.name', read_only=True)
    created_by_name = serializers.CharField(source='created_by.get_full_name', read_only=True)
    
    class Meta:
        model = InterviewQuestion
        fields = '__all__'


class InterviewApplicationSerializer(serializers.ModelSerializer):
    """面试申请序列化器"""

    student_name = serializers.CharField(source='student.name', read_only=True)
    student_id = serializers.CharField(source='student.student_id', read_only=True)
    teacher_name = serializers.CharField(source='teacher.get_full_name', read_only=True)
    status_display = serializers.CharField(source='get_status_display', read_only=True)
    type_display = serializers.CharField(source='get_interview_type_display', read_only=True)
    interview_id = serializers.SerializerMethodField()

    def get_interview_id(self, obj):
        """获取关联的面试记录ID"""
        try:
            return obj.interview.id if hasattr(obj, 'interview') else None
        except:
            return None
    
    class Meta:
        model = InterviewApplication
        fields = '__all__'
        read_only_fields = ('reviewed_at', 'review_comments', 'scheduled_date', 
                           'scheduled_time_start', 'scheduled_time_end', 'location')


class InterviewApplicationCreateSerializer(serializers.ModelSerializer):
    """面试申请创建序列化器"""
    
    class Meta:
        model = InterviewApplication
        fields = ('teacher', 'interview_type', 'title', 'description', 
                 'preferred_date', 'preferred_time_start', 'preferred_time_end')
    
    def validate_preferred_date(self, value):
        """验证期望日期不能是过去的日期"""
        if value < timezone.now().date():
            raise serializers.ValidationError("期望日期不能是过去的日期")
        return value
    
    def validate(self, data):
        """验证时间范围"""
        if data['preferred_time_start'] >= data['preferred_time_end']:
            raise serializers.ValidationError("开始时间必须早于结束时间")
        return data


class InterviewApplicationReviewSerializer(serializers.ModelSerializer):
    """面试申请审核序列化器"""
    
    class Meta:
        model = InterviewApplication
        fields = ('status', 'review_comments', 'scheduled_date', 
                 'scheduled_time_start', 'scheduled_time_end', 'location')
    
    def validate_scheduled_date(self, value):
        """验证安排日期"""
        if self.instance.status == 'approved' and not value:
            raise serializers.ValidationError("审核通过时必须设置安排日期")
        if value and value < timezone.now().date():
            raise serializers.ValidationError("安排日期不能是过去的日期")
        return value


class InterviewSerializer(serializers.ModelSerializer):
    """面试记录序列化器"""
    
    student_name = serializers.CharField(source='student.name', read_only=True)
    student_id = serializers.CharField(source='student.student_id', read_only=True)
    interviewer_name = serializers.CharField(source='interviewer.get_full_name', read_only=True)
    status_display = serializers.CharField(source='get_status_display', read_only=True)
    type_display = serializers.CharField(source='get_interview_type_display', read_only=True)
    duration = serializers.ReadOnlyField()
    
    class Meta:
        model = Interview
        fields = '__all__'


class InterviewResultSerializer(serializers.ModelSerializer):
    """面试结果序列化器"""
    
    interview_title = serializers.CharField(source='interview.title', read_only=True)
    student_name = serializers.CharField(source='interview.student.name', read_only=True)
    interviewer_name = serializers.CharField(source='interview.interviewer.get_full_name', read_only=True)
    
    class Meta:
        model = InterviewResult
        fields = '__all__'


class InterviewResultTeacherSerializer(serializers.ModelSerializer):
    """老师提交面试结果序列化器"""
    
    class Meta:
        model = InterviewResult
        fields = ('teacher_feedback', 'teacher_score', 'teacher_suggestions')
    
    def update(self, instance, validated_data):
        """更新时自动设置提交时间"""
        validated_data['teacher_submitted_at'] = timezone.now()
        instance = super().update(instance, validated_data)
        instance.check_completion()
        return instance


class InterviewResultStudentSerializer(serializers.ModelSerializer):
    """学生提交面试结果序列化器"""
    
    class Meta:
        model = InterviewResult
        fields = ('student_feedback', 'student_self_score', 'student_experience')
    
    def update(self, instance, validated_data):
        """更新时自动设置提交时间"""
        validated_data['student_submitted_at'] = timezone.now()
        instance = super().update(instance, validated_data)
        instance.check_completion()
        return instance


class InterviewEvaluationSerializer(serializers.ModelSerializer):
    """面试评价序列化器"""
    
    interview_title = serializers.CharField(source='interview.title', read_only=True)
    student_name = serializers.CharField(source='interview.student.name', read_only=True)
    average_score = serializers.ReadOnlyField()
    
    class Meta:
        model = InterviewEvaluation
        fields = '__all__'


class InterviewTaskSerializer(serializers.ModelSerializer):
    """面试任务序列化器"""
    
    student_name = serializers.CharField(source='student.name', read_only=True)
    assigned_by_name = serializers.CharField(source='assigned_by.get_full_name', read_only=True)
    status_display = serializers.CharField(source='get_status_display', read_only=True)
    questions_count = serializers.IntegerField(source='questions.count', read_only=True)
    
    class Meta:
        model = InterviewTask
        fields = '__all__'


class InterviewStatisticsSerializer(serializers.Serializer):
    """面试统计序列化器"""

    total_applications = serializers.IntegerField()
    pending_applications = serializers.IntegerField()
    approved_applications = serializers.IntegerField()
    completed_interviews = serializers.IntegerField()
    average_score = serializers.DecimalField(max_digits=4, decimal_places=2)
    this_month_interviews = serializers.IntegerField()


class PracticeMessageSerializer(serializers.ModelSerializer):
    """面试练习消息序列化器"""

    class Meta:
        model = PracticeMessage
        fields = '__all__'
        read_only_fields = ('created_at',)


class PracticeSessionSerializer(serializers.ModelSerializer):
    """面试练习会话序列化器"""

    student_name = serializers.CharField(source='student.name', read_only=True)
    student_id = serializers.CharField(source='student.student_id', read_only=True)
    status_display = serializers.CharField(source='get_status_display', read_only=True)
    messages = PracticeMessageSerializer(many=True, read_only=True)

    class Meta:
        model = PracticeSession
        fields = '__all__'
        read_only_fields = ('student', 'started_at', 'created_at', 'updated_at')


class PracticeSessionCreateSerializer(serializers.ModelSerializer):
    """面试练习会话创建序列化器"""

    class Meta:
        model = PracticeSession
        fields = ('id', 'job_id', 'job_title', 'company_name', 'conversation_id', 'status', 'started_at')
        read_only_fields = ('id', 'conversation_id', 'status', 'started_at')


class PracticeRecordSerializer(serializers.ModelSerializer):
    """面试练习记录序列化器"""

    session_info = serializers.SerializerMethodField()
    student_name = serializers.CharField(source='session.student.name', read_only=True)
    student_id = serializers.CharField(source='session.student.student_id', read_only=True)

    def get_session_info(self, obj):
        """获取会话基本信息"""
        return {
            'id': obj.session.id,
            'job_title': obj.session.job_title,
            'company_name': obj.session.company_name,
            'started_at': obj.session.started_at,
            'ended_at': obj.session.ended_at,
            'duration_minutes': obj.session.duration_minutes,
            'message_count': obj.session.message_count,
        }

    class Meta:
        model = PracticeRecord
        fields = '__all__'
        read_only_fields = ('created_at', 'updated_at')


class PracticeRecordListSerializer(serializers.ModelSerializer):
    """面试练习记录列表序列化器（简化版）"""

    student_name = serializers.CharField(source='session.student.name', read_only=True)
    student_id = serializers.CharField(source='session.student.student_id', read_only=True)
    job_title = serializers.CharField(source='session.job_title', read_only=True)
    company_name = serializers.CharField(source='session.company_name', read_only=True)
    started_at = serializers.DateTimeField(source='session.started_at', read_only=True)
    ended_at = serializers.DateTimeField(source='session.ended_at', read_only=True)
    duration_minutes = serializers.IntegerField(source='session.duration_minutes', read_only=True)
    message_count = serializers.IntegerField(source='session.message_count', read_only=True)

    class Meta:
        model = PracticeRecord
        fields = ('id', 'student_name', 'student_id', 'job_title', 'company_name',
                 'started_at', 'ended_at', 'duration_minutes', 'message_count',
                 'overall_score', 'created_at')
        read_only_fields = ('created_at',)
